package com.cloud.apigateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

/**
 *describe: zuul 自定义 限流处理器
 *
 *@author zhanghaixuan
 *@date 2018/10/02
 **/
@Component
public class RateLimterFilter extends ZuulFilter {

	private static final RateLimiter RATE_LIMITER = RateLimiter.create(100d);

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return SERVLET_DETECTION_FILTER_ORDER -1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		if(!RATE_LIMITER.tryAcquire()){
			throw new ZuulException("限流不通过1",500,"限流不通过2");
		}

		return null;
	}
}
